package treeview.container;

import search.Visitor;
import treeview.AbstractContainer;
import treeview.NodeView;

import java.awt.*;

/**
 * Created by Pavel Nikolaev
 */
public class HorizontalContainer extends AbstractContainer {
    protected int myAscent = 0;
    protected int myDescent = 0;

    @Override
    public void setLocation(int x, int y) {
        for (NodeView child : myNodeViews) {
            child.setLocation(x, y);
            x += child.getWidth();
        }
    }

    public void fitIntoWidth(Graphics g, int widthToFitInto) {
        myWidth = 0;
        myHeight = 0;
        myDescent = 0;
        myAscent = 0;
        for (NodeView child : myNodeViews) {
            child.fitIntoWidth(g, widthToFitInto);

            final int childAscent = child.getAscent();
            if (childAscent > myAscent) myAscent = childAscent;


            final int childDescent = child.getDescent();
            if (childDescent > myDescent) myDescent = childDescent;

            myWidth += child.getWidth();
        }

        setWidth(widthToFitInto);

        myHeight = myAscent + myDescent;
        align();
    }

    @Override
    public void setWidth(int width) {
        if (myWidth < width) {
            int size = myNodeViews.size();
            if (size > 0) {
                NodeView lastChild = myNodeViews.get(size - 1);
                int lastChildWidth = lastChild.getWidth() + width - myWidth;
                lastChild.setWidth(lastChildWidth);
            }
            myWidth = width;
        }
    }

    private void align() {
        for (NodeView child : myNodeViews) {
            child.setDescent(myDescent);
            child.setAscent(myAscent);
            child.setHeight(myHeight);
        }
    }

    public void drawAt(Graphics g, int x, int y) {
        myX = x;
        myY = y;
        for (NodeView child : myNodeViews) {
            child.drawAt(g, x, y);
            x += child.getWidth();
        }
    }

    public int getDescent() {
        return myDescent;
    }

    public int getAscent() {
        return myAscent;
    }

    public void setDescent(int descent) {
        myDescent = descent;
    }

    public void setAscent(int ascent) {
        myAscent = ascent;
    }

    @Override
    public void accept(Visitor visitor) {
        if (visitor.visitHorizontalContainer(this))
            super.accept(visitor);
    }
}